/*!
 * Go Bozeman Baseball Application Base Script
 * http://bozemanbaseball.com/
 *
 * Copyright 2011, Nogahide Bootstrap Inc.
 */
var $startup_team
/** 
 * ----------------------------------------------------------------------------
 *	STATUS FUNCTIONS
 * ----------------------------------------------------------------------------    
 */
(function ($){
	
    var s = "loading...";

    var defaults = {
        Site: 'http://www.bozemanbaseball.com'
		, StatusUri: '/league/Playstatus/Xj92.js'
		, TeamUri: '/team/service'
		, jQueryCache: false
		, LeagueListClass: 'league_sub_list'
		, TeamListClass: 'team_sub_list'
		, Debug : true
    };
	
	var cacheExpire = 1000*60*60*2; // 2 hour Status cache
	var d = new Date();
    var cachetime = d.getTime();
		    
    // clone the defaults
    var _CurrentOptions = $.extend({}, defaults);
    
    // selector funcitons
    $.fn.bozLoadStatus = function(newOptions, callback, force)
    {
		if (jQuery.type(newOptions) == 'function') {
			force = callback;
			callback = newOptions;		
			var _Options = $.bozStatus.updateOptions(null);
		}
		else {
			var _Options = $.bozStatus.updateOptions(newOptions);
		}
		
    	var LoadStatusTo = $(this);
    	
    	debug('-newOptions: ' + typeof(newOptions));
    	debug('-callback: ' + typeof(callback));
    	
		// check cache
		if (unCacheBozStatus() && !force) {
			debug('**CACHED STATUS**');
			$(LoadStatusTo).bozSetStatus(newOptions, callback);
		}
		else {
			debug('-loading script');
			var URI = _Options.Site + _Options.StatusUri;
			debug(' - ' + URI);
			$.getScript(URI, function(){
				debug('-- END loading script');
				cacheBozStatus();
				$(LoadStatusTo).bozSetStatus(newOptions, callback);
			});
		}

    };
	
	function cacheBozStatus()
	{		
		cache('bozUpdated', cachetime);
		
		cacheObject('LeagueClasses', $.bozStatus.$LeagueClasses);
			
		cacheObject('PlayStatus', $.bozStatus.$PlayStatus);
			
		cacheObject('Leagues', $.bozStatus.$Leagues);
			
		cacheObject('Teams', $.bozStatus.$Teams);	
	}
	
	function unCacheBozStatus()
	{
		var cacheTimestamp = parseInt(storage.getItem('bozUpdated')) || cachetime;
		
		// the cache is expired and needs reset
		if ((cachetime - cacheTimestamp) > cacheExpire) return false;
		
		$.bozStatus.$LeagueClasses = cacheObject('LeagueClasses');
		$.bozStatus.$PlayStatus = cacheObject('PlayStatus');
		$.bozStatus.$Leagues = cacheObject('Leagues');
		$.bozStatus.$Teams = cacheObject('Teams');
		
		// @todo: cache data

		return (jQuery.type($.bozStatus.$LeagueClasses) == 'object')
	}
    
	$.fn.bozSetStatus = function(newOptions, callback)
    {
		debug('STATUS -- bozSetStatus:');
		if (typeof(newOptions) == 'function')
		{
			debug('-swapping newOptions and callback');
			callback = newOptions;
    		newOptions = {};
		}
    	if (typeof(callback) != 'function')
		{
    		debug('-setting callback dummy :' + typeof(callback));
    		callback = function(){debug('dummy callback');};
		}
    	var _Options = $.bozStatus.updateOptions(newOptions);
    	
		$(this).empty();
    	for (var LeagueClass in $.bozStatus.$PlayStatus)
    	{
    		Status = $.bozStatus.$PlayStatus[LeagueClass];
    		Status.name = LeagueClass;
    		
    		League = $.bozStatus.$LeagueClasses[LeagueClass];
    		
    		StatusIconClass = getStatusIconClass(Status.status_class);
    			
    		Merge = $.extend({ status_icon_class: StatusIconClass }, League, Status);
    		
    		var LeagueClassListItem = $.tmpl( $.bozStatus.$LeagueClassTemplate, Merge );
    		LeagueClassListItem.appendTo( $(this) );
    		
    		debug('-calling bozAppendLeagues for league class: ' + LeagueClass + ' to ' + LeagueClass + '_list');
			debug('appending to count ' + $('#' + LeagueClass + '_list').length);
    		$('#' + LeagueClass + '_list').bozAppendLeagues($.bozStatus.$Leagues[LeagueClass]);
    	}
    	
    	$(this).listview("refresh"); 
    	debug('calling bozSetStatus callback')
    	callCallback(callback);
    	
    	return this;
    	
    };
    
    $.fn.bozAppendLeagues = function(Leagues, NewOptions, callback)
    {
    	debug('Leagues -- bozAppendLeagues:');
		
    	if (typeof(newOptions) == 'function')
  		{
      		callback = newOptions;
      		newOptions = {};
  		}
    	if (typeof(callback) != 'function')
  		{
      		callback = function(){};
  		}
    	
    	var _Options = $.bozStatus.updateOptions(NewOptions);
    	
    	for (var LeagueKey in Leagues)
  		{
      		debug('-rendering leagues for ' + LeagueKey);
      		var _League = Leagues[LeagueKey];
			
      		var LeagueListItem = $.tmpl( $.bozStatus.$LeagueListTemplate, _League );
      		LeagueListItem.appendTo( $(this) );
      		
      		debug('appending teams for ' + _League.code);
      		var _Teams = $.bozStatus.$Teams[_League.code];
      		if (typeof(_Teams) != 'undefined')
      			$(LeagueListItem).find('.' + $.bozStatus.TeamListClass).bozAppendTeams(_Teams);
  		}
    	
		//$(this).listview("refresh"); 
		
    	if (typeof(callback) == 'function')
  		{
      		callback();
  		}
    	
    	return this;
    };
    
    $.fn.bozAppendTeams = function(Teams, NewOptions, callback)
    {
    	debug('TEAMS -- bozAppendTeams:');
    	if (typeof(newOptions) == 'function')
		{
    		callback = newOptions;
    		newOptions = {};
		}
    	
    	var _Options = $.bozStatus.updateOptions(NewOptions);
    	for (var TeamKey in Teams)
		{
    		var _Team_ = $.extend({}, _Options, Teams[TeamKey]); 
    		var TeamListItem = $.tmpl( $.bozStatus.$TeamListTemplate,  _Team_);
    		if (typeof(TeamListItem) == 'object') TeamListItem.appendTo( $(this) );
		}
    	
    	if (typeof(callback) == 'function')
		{
    		callback();
		}
    	
    	return this;
    };
    
    // init the namespace if not already
    if (typeof($.bozStatus) == 'undefined')  $.bozStatus = {};
    
    // static functions
    $.bozStatus.updateOptions = function(newOptions)
    {
    	if (typeof(newOptions) != undefined)
    		_CurrentOptions = $.extend({}, defaults, _CurrentOptions, newOptions);
    	
    	// Set global options
    	$.ajaxSetup ({
    	    cache: _CurrentOptions.jQueryCache
    	});
    	
    	return _CurrentOptions;
    };
    
    function getStatusIconClass(StatusClass)
    {
    	var StatusIconClass = 'false';
		switch (StatusClass) { 
	        case 'org_status_good': 
	        	StatusIconClass = 'false';
	            break; //end org_status_good 
	
	        case 'org_status_caution': 
	        	StatusIconClass = 'info';
	        	break; //end org_status_caution
	            
	        case 'org_status_canceled': 
	        	StatusIconClass = 'alert';
	        	break; //end org_status_canceled
	            
	        default: 
	        	StatusIconClass = 'false';
        		break; 
    	}
		
		return StatusIconClass;
    }
    
    // init namespace server vars
    if (typeof($.bozStatus.$PlayStatus) == 'undefined') $.bozStatus.$PlayStatus = {};
    if (typeof($.bozStatus.$LeagueClasses) == 'undefined') $.bozStatus.$LeagueClasses = {};
    if (typeof($.bozStatus.$Leagues) == 'undefined') $.bozStatus.$Leagues = {};
    if (typeof($.bozStatus.$Teams) == 'undefined') $.bozStatus.$Teams = {};
    
    $.bozStatus.$LeagueClassTemplate = $.template(null, "<li class='${status_class}'>" +
    		"<span style='float:right;'><img class='orgicon' style='position: inherit; max-height: 50px;' src='images/${code}_blkBorder_med.png' title='${description}'/></span>" +
    		"<h3>${description}</h3>" +
    		"<p>${status_text}</p>" + 
    		"<ul id='${code}_list' data-role='listview' data-inset='true'></ul></li>");
    
    $.bozStatus.LeagueListClass = 'league_sub_list';
    
    $.bozStatus.$LeagueListTemplate = $.template(null, "<li class='ui-btn' data-transition='slide'>" +
    		"<h3>${name}</h3>" +
    		"<p>${description}</p>" +
    		"<ul class='team_sub_list' data-role='listview' data-inset='true'><ul>" +
    		"</li>");
    		
    $.bozStatus.TeamListClass = 'team_sub_list';
    
    $.bozStatus.$TeamListTemplate = $.template(null, "<li class='ui-li ui-li-has-thumb' data-icon='${status_icon_class}' data-transition='slide'>" +
    		"<a onClick=\"loadTeam('${id}')\" data-transition='slide' ><img class='team-thumb ui-li-thumb' src='${Site}/themes/bozball/images/teams/${name_code}_med.compressed.png'/>" +
    		"<h3>${name} </h3>" +
    		"<p>${sponsor}</p></a>" +
    		"</li>");
    /**
     * END STATUS
     */
    $.bozStatus.updateOptions({
    	'PlayersHome' : 'players_page',
    	'CoachesList' : 'coach_list',
    	'GamesHome' : 'games_page'
    });
    
    $.fn.bozLoadTeam = function(TeamId, newOptions, callback)
    {
    	TeamId = parseInt(TeamId);
    	if (TeamId < 1) return;
    	
    	var LoadTeamTo = $(this);
    	
    	if (typeof(newOptions) == 'function')
		{
			debug('-swapping newOptions and callback');
			callback = newOptions;
    		newOptions = {};
		}
    	if (typeof(callback) != 'function')
		{
    		debug('-setting callback dummy :' + typeof(callback));
    		callback = function(){debug('dummy callback');};
		}
    	
    	var _Options = $.bozStatus.updateOptions(newOptions);
		$('#team_display').html('<h1><i>Loading...</i></hi>');
		$.bozStatus.$Team = cacheObject('team_' + TeamId);
		if (isObject($.bozStatus.$Team)) {
			$(LoadTeamTo).bozShowTeam(_Options, callback);
		}
		else {
			$.getScript(_Options.Site + _Options.TeamUri + '?team_id=' + TeamId, function(){
				$(LoadTeamTo).bozShowTeam(_Options, callback);
				cacheObject('team_' + TeamId, $.bozStatus.$Team);
			});
		}
    };
    
    $.fn.bozShowTeam = function(newOptions, callback)
    {
    	if (typeof(newOptions) == 'function')
		{
			debug('-swapping newOptions and callback');
			callback = newOptions;
    		newOptions = {};
		}
    	if (typeof(callback) != 'function')
		{
    		debug('-setting callback dummy :' + typeof(callback));
    		callback = function(){debug('dummy callback');};
		}
    	
    	var _Options = $.bozStatus.updateOptions(newOptions);
    	var DomContext = $(this);
    	var teamDisplay = $('#team_display');
		
    	var _Team_ = $.extend({}, _Options, $.bozStatus.$Team);
    	var TeamItem = $.tmpl( $.bozStatus.$TeamDisplayTemplate, _Team_);
		
		if (isObject(TeamItem)) teamDisplay.html(TeamItem);
		
		$('.teamname').html(_Team_.name);
		
		var _CoachesList_ = $('#' + _Options.CoachesList).empty();
		$.each($.bozStatus.$Team.coaches,function()
		{
			var _Coach_ = $.extend({}, _Options, this);
			var Item = $.tmpl( $.bozStatus.$TeamCoachesTemplate, _Coach_);
			if (typeof(Item) == 'object') Item.appendTo( _CoachesList_ );
		});
		//_CoachesList_.listview("refresh");
		
		var _PlayersList_ = $('#' + _Options.PlayersHome).find('.list').empty(); 
		$.each($.bozStatus.$Team.players,function()
		{
			var _Player_ = $.extend({}, _Options, this);
			var Item = $.tmpl( $.bozStatus.$TeamPlayerstTemplate, _Player_);
			if (typeof(Item) == 'object') Item.appendTo( _PlayersList_ );
		});
		//_PlayersList_.listview("refresh");
		
		
		var _GamesList_ = $('#' + _Options.GamesHome).find('.list').empty();
		debug(_Options.GamesHome + ': ' + _GamesList_.length);
		$.each($.bozStatus.$Team.games,function()
		{
			var _Game_ = $.extend({}, _Options, this);
			var Item = $.tmpl( $.bozStatus.$TeamGamesTemplate, _Game_);
			if (typeof(Item) == 'object') Item.appendTo( _GamesList_ );
		});
		//_GamesList_.listview("refresh");
		
    	
    	callback();
    };
    
    $.bozStatus.$TeamDisplayTemplate = $.template(null, "<img class='left' title='${name}' src='${Site}/themes/bozball/images/teams/${name_code}_med.compressed.png' />" +
    		"<h1>${name}</h1>" +
    		"<h2 class=''>${sponsor}</h2>" +
    		"${total_wins} wins and ${total_losses} losses");
    
    $.bozStatus.$TeamPlayerstTemplate = $.template(null, "<li>" +
    		"<h3>${name_first} ${name_last}</h3>" +
			"</li>");
    
    $.bozStatus.$TeamCoachesTemplate = $.template(null, "<li>" +
    		"<h4>${name_first} ${name_last} <small>${type}</small></h4>" +
    		"<p><a href='tel:${phone}'>${phone}</a></p>" +
    		"<p><a href='mailto:${email}'>${email}</a></p>" +
    		"</li>");
    
    $.bozStatus.$TeamGamesTemplate = $.template(null, "<li>" +
    		"<p>${date}</p>" +
    		"<h3>"+
    		"<small>(H)</small>${team_one} <i>VS</i> "+
    		"<small>(V)</small>${team_two} "+
    		"</h3>" +
    		"<p>${location}</p>" +
    		"</li>");
    
    
    
/** 
 * ----------------------------------------------------------------------------
 *	UTILITY FUNCTIONS
 * ----------------------------------------------------------------------------    
 */

	var rssCacheExpire = 1000*60*60*2; // 2 hour Status cache
	
	// RSS Reading
	// load everyone feed
	$.fn.bozLoadEveryoneFeed = function(callback, reload)
	{
		if (jQuery.type(reload) != "undefined"
			&& reload === true) unCache($.bozStatus.EveryoneFeedUrl);
		
		$(this).getFeedCached($.bozStatus.EveryoneFeedUrl, callback);
	};
	
	$.fn.getFeedCached = function(url, callback)
	{
		var cached = cacheObject(url);
		debug('cached type ' + jQuery.type(cached));
		
		$target = $(this);
		if (isObject(cached)) {
			AppendFeed($target, cached, callback);
		}
		else {
			LoadFormattedFeed(url, $.bozStatus.$RSSTpl, function(feed){
				cacheObject(url, feed);
				AppendFeed($target, feed, callback);
			});
		}
	}
	
	function AppendFeed(target, feed, callback)
	{
		$.each(feed, function(index, itemValue){
						if (index > 3) return false;
						$(target).append(itemValue);
					});
		$(target).find('a').button(); 
		callCallback(callback);
	}
	
	// fetches and formats an array of feed items
	function LoadFormattedFeed(url, item_template, LoadFormattedFeedCallback)
	{
		LoadFeed(url, function(items){
			var retFeed = [];
			$.each(items, function(index, itemValue){
				itemValue.key = 'story_' + index;
				retFeed.push($.tmpl($.bozStatus.$RSSTpl, itemValue));
				var rsspage = $.tmpl($.bozStatus.$RSSPageTpl, itemValue);
				$('body').append(rsspage);				
			});
			callCallback(LoadFormattedFeedCallback, retFeed);
		});
	}
	
	// fetches an array of feed items
	function LoadFeed(url, LoadFeedCallback){
		$.get(url, function(data){
			var processed = ProcessFeed(data)
			callCallback(LoadFeedCallback, processed);
		});
	}
	
	// process xml data
	function ProcessFeed(data) 
	{
		var items = [];
		var $xml = $(data);
		$xml.find("item").each(function() {
	        var $this = $(this);
            items.push( {
                title: $this.find("title").text(),
                link: $this.find("link").text(),
                description: $this.find("description").text(),
                date: $this.find("pubDate").text(),
                author: $this.find("dc:creator").text(),
				category: $this.find("category").text()
        	} );
	    });
		return items;
	}
	
	$.bozStatus.EveryoneFeedUrl = 'http://www.bozemanbaseball.com/blog/category/everyone/feed/';
	
	$.bozStatus.$RSSTpl = $.template(null, "" +
    		"<a href='#${key}' data-role='button'>${title}</a>" +
    		"");
	
	$.bozStatus.$RSSPageTpl = $.template(null, "<div data-role='page' id='${key}' data-theme='a' data-add-back-btn='true'>"+
			"<div data-role='header'><h3>${title}</h3></div>"+
			"<div data-role='content' data-theme='a'>" + 
				"<p>${description}</p>" +
	    		"<p><small>${author} in ${category} on ${date}</small></p>" +
	    		"<p><small><a href='${link}'>view on web</a></small></p>" +
			"</div>"+
			"<div data-role='footer'><small style='float:right;margin:8px'>&copy;2011 Bozeman Baseball</small></div>"+
		"</div>");
	
	$.bozStatus.$PageTpl = $.template(null, "<div data-role='page' id='two' data-theme='a' data-add-back-btn='true'>"+
				"<div data-role='header'>${header}</div>"+
				"<div data-role='content' data-theme='a'>${content}</div>"+
				"<div data-role='footer'>${footer}</div>"+
			"</div>");
	
	// URL PARSING
	// preparse parameters
	var _ParameterCache = (function(a) {
        if (a == "") return {};
        var b = {};
        jQuery.each( a, function(Key, Value) {
        	var p=Value.split('=');
        	if (p.length != 2) return;
        	b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        });
        return b;
    })(window.location.search.substr(1).split('&'))

	
	$.urlParameter = function(Name)
	{
		// try again to get the value if it is not present
		if (typeof(_ParameterCache[Name]) == 'undefined')
		{
		    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);

			_ParameterCache[Name] = match && decodeURIComponent(match[1].replace(/\+/g, ' '));

		}
		
		return _ParameterCache[Name];
	};

	// SCRIPT LOADING
	// load script from the server via script link
	$.getScript = function(Uri, StatusLoadedcallback)
	{
		if (typeof(StatusLoadedcallback) == 'function')
		{
			window.getScriptLoaded = StatusLoadedcallback;
		}
		
		// avoid cache always by adding unique salt to the url
		var Date_ = new Date();
		
		prefix = (Uri.search('/\?/')) ? '&' : '?'; 
		var salt = prefix + '_=' + parseInt(Date_.getTime() / 1000);
		debug('getting script : ' + Uri + salt);
			
		var $cript = document.createElement('script');
		$cript.setAttribute('type', 'text/javascript');
		$cript.setAttribute('src', Uri + salt);
		$($cript).appendTo( "head" );
	};
	
    function debug(string)
    {
    	if (_CurrentOptions.Debug && typeof(console) != 'undefined')
		{
    		if (typeof(string) == 'object')
    		{
    			console.dir(string);
    		}
    		else
			{
    			console.log(string);
			}
		}
    };
	
	function isObject(param)
	{
		return (jQuery.type(param) == 'object')
	}
	
	// set up storage - mocked if not supported
	var storage = window.localStorage || {
		key : function(){},
		setItem : function(){},
		getItem : function(){},
		removeItem : function(){},
		clear : function(){}
	};
	
	function unCache(key)
	{
		storage.removeItem(key);
	}
	
	// deal with string cache
	function cache(key, value)
	{
		if (isObject(value))
		{
			// deal with the object cache
			cacheObject(key, value)
		}
		else if (jQuery.type(value) == 'undefined')
		{
			// GET the itme from storage
			return storage.getItem('bzb_' + key);
		}
		else
		{
			// SET the item in storage
			storage.setItem('bzb_' + key, value);
			return;
		}
	}
	// deal with object cache
	function cacheObject(key, object)
	{
		// fetch object
		if (isObject(object))
		{
			// serialize object
			cache(key, JSON.stringify(object));
			return object;
		}
		else
		{
			var cachedString = cache(key);
			if (cachedString)
			{
				return JSON.parse(cachedString);
			}
			// if nothing was in cache
			return cachedString;
			
		}
	}
	
	function callCallback(callback, params)
	{
		if (jQuery.type(callback) == "function")
		{
			callback(params);
		}
	}
	
	$.bozStatus.init = function(){
	
		$startup_team = cache('startup_team');
		$('#startup_button').click(function(){
			if ($startup_team == $.bozStatus.$Team.id) {
				debug('turning off team ' + $.bozStatus.$Team.id);
				unCache('startup_team');
				cache('startup_team', 0);
				$('#startup_button').removeClass('ui-btn-active');
			}
			else {
				debug('turning ON team ' + $.bozStatus.$Team.id);
				$startup_team = $.bozStatus.$Team.id
				cache('startup_team', $.bozStatus.$Team.id);
				$('#startup_button').addClass('ui-btn-active');
			}
		});
		
		$('#refresh_button').click(function(){
			loadOrg(this, true);
		});
		
		$('#refresh_rss_button').click(function(){
			loadRss(this, true)
		});
		
		loadOrg($('#refresh_button'), false, function(){
			debug('**loading startup team:' + $startup_team + '**');
			loadTeam($startup_team);
		});
		
		loadRss($('#refresh_rss_button'));
	};
		
})(jQuery);

/** 
 * ----------------------------------------------------------------------------
 *	CLIENT FUNCTIONS
 * ----------------------------------------------------------------------------    
 */
function loadOrg(clicked, force, loadOrgCallBack)
{
	showLoading();
			
	var _clickedButton = $(clicked);
	_clickedButton.addClass('ui-disabled');
	
	$( "#status_list" ).empty().bozLoadStatus(function()
	{
		console.log('---------- CALLCACK');
		$(_clickedButton).removeClass('ui-disabled');
		if (jQuery.type(loadOrgCallBack) == "function") loadOrgCallBack();
		showLoading(false);
	}, force);
}

function loadRss(clicked, force)
{
	showLoading();
	
	var _clickedButton = $(clicked);
	_clickedButton.addClass('ui-disabled');
	
	$('#blogpost').empty().bozLoadEveryoneFeed(function(){
		$(_clickedButton).removeClass('ui-disabled');
		showLoading(false);
	}, force);
}

function loadTeam(id)
{
	if (id){}else{ return; }
	console.log('###loading team ' + id);
	showLoading();
	$('#team_home').bozLoadTeam(id, function(){
		showLoading(false);
		if ($startup_team == $.bozStatus.$Team.id)
		{
			$('#startup_button').addClass('ui-btn-active');
		}
		else
		{
			$('#startup_button').removeClass('ui-btn-active');
		}
		$.mobile.changePage($('#team_home'), {
			transition: "flip"
		});
		console.log('done loading');
	});
}

var loading = 0;

function showLoading(should)
{
	if (should == null || should == true)
	{
		if (loading < 1)
		{
			$.mobile.showPageLoadingMsg();
		}
		loading=loading+1;
	}
	else
	{
		loading--;
		if (loading < 1)
		{
			$.mobile.hidePageLoadingMsg();
		}
	}
}